package com.laoyao.service;

import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.aop.Duang;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

public class TypeService {
	public static final TypeService me = Duang.duang(TypeService.class);
	private static TypeService dao = Duang.duang(TypeService.class);
	
	public boolean isExistsType1(String typeName){
		String sql = "select * from v_type_1 where typeName= ?";
		return Db.findFirst(sql,typeName)!=null;
	}
	public boolean isExistsType2(String typeName,Integer id){
		String sql = "select * from v_type_2 where typeName= ? and type1Id=?";
		return Db.findFirst(sql,typeName,id)!=null;
	}
	
	/**
	 * 根据一级分类删除二级分类
	 */
	@Before(Tx.class)
	public boolean delByType1Id(Integer type1Id){
		String sql = "delete from v_type_2 where type1Id=?";
		return Db.update(sql,type1Id)>0;
	}
	
	/**
	 * 返回一级分类列表
	 */
	public Page<Record> type1List(Integer pageNumber,Integer pageSize){
		String sql = "select * from v_type_1 order by rank desc";
		return Db.paginate(pageNumber, pageSize, sql);
	}
	/**
	 * 返回二级分类列表
	 */
	public Page<Record> type2List(Integer pageNumber,Integer pageSize,Integer id){
		String sql = "select a.*,b.typeName type1Name from v_type_2 a ,v_type_1 b where a.type1Id = b.id and a.type1Id=?"
				+ " order by b.rank desc,a.rank desc";
		return Db.paginate(pageNumber, pageSize, sql,id);
	}
	/**
	 * 判断类型1是否可删除
	 * @param id
	 * @return
	 */
	public boolean isEnableDelType1(Integer id){
		String sql = "select * from v_video where type1Id=?";
		return Db.findFirst(sql,id)==null;
	}
	/**
	 * 判断类型2是否可删除
	 * @param id
	 * @return
	 */
	public boolean isEnableDelType2(Integer id){
		String sql = "select * from v_video where type1Id=?";
		return Db.findFirst(sql,id)==null;
	}
	
	/**
	 * 讲一级分类二级分类直接打包
	 * @return
	 */
	public List<Record> getType(){
		
		//获取一级分类数据
		String sql = "select * from v_type_1";
		String sql2 = "select * from v_type_2 where type1Id=?";
		List<Record> list = Db.find(sql);
		
		for(int i = 0;i<list.size();i++){
			
			List<Record> type2 = Db.find(sql2,list.get(i).getInt("id"));
						
			list.get(i).set("children",type2);
		}
		
		return list;
	}

}
